layui.define([], function (exports) {
	"use strict";
	var YsModal = layui.YsModal, object = {
			c: {data:[]}, // 配置项
			f: function (c) { // 数据初始化
				var s = new Date().getTime(),t = this;
				
				t.c.draftId = 0;
				t.c.id_tree_org = 'id_tree_org'; // 组织机构树的ID
				t.c.id_tree_group = 'id_tree_group'; // 用户组树的ID

				t.c.selectedDatas_receiver = []; // 选中的收件人
				t.c.selectedDatas_copyer = []; // 选中的抄送人
				t.c.selectedDatas_tag = []; // 选中的邮件标签
				t.c.id_form_for_witer = 'id_form_write_mail'; // 写邮件的表单ID

				t.c.MAP_DICT_Emergent = [{value: 1, name: '<span style="color: blue;">普通</span>'}, {value: 2, name: '<span style="color: orange;">加急</span>'}, {value: 3, name: '<span style="color: red;">特急</span>'}];
				t.c.MAP_DICT_StateRead = [{value: 0, name: '<span style="color: red;">未读</span>'}, {value: 1, name: '<span style="color: green;">已读</span>'}];
				
				t.c.inbox = {
					loaded: 0,
					showContented: 0,
					id_panel: 'id_panel_inbox',
					id_table: 'id_main_table_inbox',
					filter_table: 'filter_main_table_inbox'
				} // 收件箱的配置，同步前端ID
				t.c.draft = {
					loaded: 0,
					showContented: 0,
					id_panel: 'id_panel_draft',
					id_table: 'id_main_table_draft',
					filter_table: 'filter_main_table_draft'
				} // 草稿箱的配置，同步前端ID
				t.c.outbox = {
					loaded: 0,
					showContented: 0,
					id_panel: 'id_panel_outbox',
					id_table: 'id_main_table_outbox',
					filter_table: 'filter_main_table_outbox'
				} // 发件箱的配置，同步前端ID
				t.c.dustbin = {
					loaded: 0,
					showContented: 0,
					id_panel: 'id_panel_dustbin',
					id_table: 'id_main_table_dustbin',
					filter_table: 'filter_main_table_dustbin'
				} // 垃圾箱的配置，同步前端ID
				t.c.detail = {
						loaded: 0,
						showContented: 0,
						id_panel: 'id_panel_detail'
					} // 详情的配置，同步前端ID
			},
			load:function () {
				var t = this;
				
				this.initDraft(); // 初始化草稿
				this.loadDtreeOrg(); // 加载组织机构树
				this.loadDtreeGroup(); // 加载用户组树
				this.loadTableOfInbox(); // 默认只加载收件箱的内容
				this.bindModalSelector(); // 绑定选择收件人、抄送人或邮件标签
				this.bindClickBtn(); // 绑定按钮点击
				
				// 定时默默保存草稿
				setInterval(function () {
					t.saveDraftOnly();
			    }, 30000);
			},
			initDraft:function () { // 初始化草稿
				var t = this;
				var indexOfLoading = layer.load(1, {
					shade: [0.5,'#000000'] //0.1透明度的白色背景
				});
				$.ajax({
					async: false, // 同步获取
					type: "POST",
					url: '/api/inter/mail/initInfoForWrite',
					data: {},
					success: function (res) {
						if (res.code == 0) {
							// 更新收件人
							t.doUpdateUsersForReceiver(res.data.receiverArr);
							// 更新抄送人
							t.doUpdateUsersForCopyer(res.data.copyerArr);
							// 更新标签
							t.doUpdateOptionsForTag(res.data.tagArr);

							// 更新草稿ID
							t.doUpdateWriteOfDraftId(res.data.id);
							// 更新标题
							t.doUpdateWriteOfTitle(res.data.title);
							// 更新紧急程度
							t.doUpdateWriteOfEmergent(res.data.emergent);
							t.initHypeTextEditor(res.data.detail);
							
							// 发件人更新
							t.c.senderUserId = res.data.senderUserId;
							t.c.senderUserName = res.data.senderUserName;
							
							t.bindFileMultyOfDraft(); // 绑定草稿附件按钮点击
						} else {
							layer.msg(res.msg);
						}
						layer.close(indexOfLoading);
					}
				});
			},
			loadDtreeOrg:function () { // 初始化邮件联系人
				var t = this;
				
				// 初始化邮件联系人
				var DemoTree = layui.dtree.render({
					elem: "#" + t.c.id_tree_org,
					url: '/api/inter/tsOrganizationInfo/dtree',
					initLevel: "2",
					icon: -1,
					toolbar:true,
					toolbarWay:"follow",
					toolbarShow:[],
					width:'100%',
					menubar:false,
					toolbarExt: [{
						toolbarId: "add",
						icon: "dtree-icon-add-circle",
						title: "添加进",
						handler: function (node, $div) {
							layer.confirm('确定加入该机构及其子机构下的人员？ ', {
								btn: ['确定','取消'] //按钮
							}, function(){
								var indexOfLoading = layer.load(1, {
									shade: [0.5,'#000000'] //0.1透明度的白色背景
								});
							}, function(){}
							);
						}
					}]
				});

				// 绑定组织机构树的节点点击
				layui.dtree.on('node("' + t.c.id_tree_org + '")' ,function(obj){
					var objd = obj.param;
				});
			},
			loadDtreeGroup:function () { // 加载用户组
				var t = this;
				var DemoTree2 = layui.dtree.render({
					elem: "#" + t.c.id_tree_group,
					url: '/api/inter/mailGroup/dtree',
					initLevel: "2",
					icon: -1,
					toolbar:true,
					toolbarWay:"follow",
					toolbarShow:[],
					width:'100%',
					menubar:true,
					menubarTips:{
						group:["refresh", {
							menubarId: "addGroup",  // 按钮的唯一ID
							icon: "dtree-icon-roundadd", // 从dtreefont库中选取
							title: "新增用户组",  // 按钮的提示标题
							handler: function(node, $div){  //扩展按钮的回调函数
								layer.open({
									type: 2,
									title: "新增用户组",
									area: ['95%', '90%'],
									content: '/web/mail/mailGroup/toAdd'
								});
							}
						}]
					},
					toolbarExt: [{
						toolbarId: "addUser",
						icon: "dtree-icon-add-circle",
						title: "添加用户",
						handler: function (node, $div) {
							
							if (node.level > 1) {
								layer.msg('非组别数据，无法操作');
								return;
							}
							
							var groupId = node.nodeId;
							// 获取组别下的用户
							$.ajax({
								type: "POST",
								url: '/api/inter/mailGroup/listUser',
								data: {
									groupId: groupId
								},
								success: function (res) {
									if (res.code == 0) {
										var selectedDatas = [];
										var rows = res.data.rows;
										for (var i = 0; i < rows.length; i++) {
											selectedDatas.push({
												userId: rows[i].userId
											});
										}
										layui.YsModal.init({modalKey: 'TS_UserInfo', type: 'checkbox', uniqueKey: 'userId', parentObj: t, selectedData: selectedDatas, extraData:{useIn: 'select_users_for_group', groupId: groupId}});
									} else {
										layer.msg(res.msg);
									}
								}
							});
						}
					},{
						toolbarId: "edit",
						icon: "dtree-icon-bianji",
						title: "编辑此用户组",
						handler: function (node, $div) {
							
							if (node.level > 1) {
								layer.msg('非组别数据，无法操作');
								return;
							}
							
							var content, title, url;
							layer.open({
								type: 2,
								title: "编辑",
								area: ['95%', '90%'],
								content: '/web/mail/mailGroup/toEdit?id=' + node.nodeId
							});
						}
					}]
				});

				// 绑定用户组树的节点点击
				layui.dtree.on('node("' + t.c.id_tree_group + '")' ,function(obj){
					var objd = obj.param;
				});
			},
			loadTableOfInbox: function() {
				var t = this;
				
				var loaded = t.c.inbox.loaded;
				if(t.c.inbox.loaded == 1) {
					return;
				}
				t.c.inbox.loaded = 1;
				
				// 初始化列表-收件箱
				layui.table.render({
					elem: '#' + t.c.inbox.id_table
					,url: '/api/inter/mail/searchForInbox'
					,toolbar: '#toolbar_for_1'
					,defaultToolbar: ['filter']
					,height: 'full-20' // 最大高度减去其他容器已占有的高度差
					,limit : 50
					,limits : [50,100,200,500]
					,where: {}
					,cellMinWidth: 95
					,totalRow: false // 开启合计行，true开启，false关闭
					,page: true
					,request: {
						pageName: 'page',
						limitName: 'size'
					}
					,even: false // 开启隔行背景
					,cols: [ [
							 {title:'', type:'checkbox', fixed:'left', unresize:true, width: 50}
							 ,{field:'title', width:300, title: '主题', align: 'center'}
							 ,{field:'createUserId', width:200, title: '发件人', align: 'center'}
							 ,{field:'copyers', width:200, title: '抄送', align: 'center'}
							 ,{field:'tags', width:200, title: '邮件标签', align: 'center'}
							 ,{field:'extraFile', width:80, title: '附件', align: 'center'}
							 ,{field:'emergent', width:80, title: '紧急程度', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_Emergent.length; i++) {
										var option = t.c.MAP_DICT_Emergent[i];
										if (option.value == d.emergent) {
											return option.name;
										}
									}
									return ``;
								}
							 }
							 ,{field:'stateRead', width:80, title: '阅读状态', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_StateRead.length; i++) {
										var option = t.c.MAP_DICT_StateRead[i];
										if (option.value == d.stateRead) {
											return option.name;
										}
									}
									return ``;
								}
							 }
						   ] ]
					,done: function(res){
					}
					,error: function(res, msg){
						console.log(res, msg)
					}
				});

				// 工具栏事件-收件箱
				layui.table.on('toolbar(' + t.c.inbox.filter_table + ')', function(obj){
					var id = obj.config.id;
					var checkStatus = layui.table.checkStatus(id);
					var datas = checkStatus.data;
					var othis = lay(this);

					switch(obj.event){
						case 'batch_delete':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("确定放入回收站？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/deleteBatchFromInbox',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
						case 'batch_readed':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("确定标记已读？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/readBatchFromInbox',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
					};
				});
				
				//行单击事件
				layui.table.on('row(' + t.c.inbox.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.mainId,
							type: 'inbox'
						},
						success: function (res) {
							if (res.code == 0) {
								t.showContentOnGrid(res.data.content, t.c.inbox);
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
				
				//行双击事件
				layui.table.on('rowDouble(' + t.c.inbox.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.mainId,
							type: 'inbox'
						},
						success: function (res) {
							if (res.code == 0) {
								t.updateContentOfDetail(res.data);
								t.showItem('detail', 'inbox');
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
			},
			loadTableOfDraft: function() { // 加载草稿箱
				var t = this;
				
				var loaded = t.c.draft.loaded;
				if(t.c.draft.loaded == 1) {
					return;
				}
				t.c.draft.loaded = 1;
				
				// 初始化列表-收件箱
				layui.table.render({
					elem: '#' + t.c.draft.id_table
					,url: '/api/inter/mailDraft/search'
					,toolbar: '#toolbar_for_2'
					,defaultToolbar: ['filter']
					,height: 'full-20' // 最大高度减去其他容器已占有的高度差
					,limit : 50
					,limits : [50,100,200,500]
					,where: {}
					,cellMinWidth: 95
					,totalRow: true // 开启合计行，true开启，false关闭
					,page: true
					,request: {
						pageName: 'page',
						limitName: 'size'
					}
					,even: false // 开启隔行背景
					,totalRow: true
					,cols: [ [
							 {title:'', type:'checkbox', fixed:'left', unresize:true, width: 50}
							 ,{field:'title', width:300, title: '主题', align: 'center'}
							 ,{field:'createUserId', width:200, title: '发件人', align: 'center'}
							 ,{field:'copyers', width:200, title: '抄送', align: 'center'}
							 ,{field:'tags', width:200, title: '邮件标签', align: 'center'}
							 ,{field:'extraFile', width:80, title: '附件', align: 'center'}
							 ,{field:'emergent', width:80, title: '紧急程度', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_Emergent.length; i++) {
										var option = t.c.MAP_DICT_Emergent[i];
										if (option.value == d.emergent) {
											return option.name;
										}
									}
									return ``;
								}
							 }
						   ] ]
					,done: function(res){
						
					}
					,error: function(res, msg){
						console.log(res, msg)
					}
				});

				// 工具栏事件-草稿箱
				layui.table.on('toolbar(' + t.c.draft.filter_table + ')', function(obj){
					var id = obj.config.id;
					var checkStatus = layui.table.checkStatus(id);
					var datas = checkStatus.data;
					var othis = lay(this);

					switch(obj.event){
						case 'batch_delete':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("确定删除？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/deleteBatchFromDraft',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
												
												t.initDraft();
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
					};
				});
				
				//行单击事件
				layui.table.on('row(' + t.c.draft.filter_table + ')', function(obj){
					var content = ``;
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.id,
							type: 'draft'
						},
						success: function (res) {
							if (res.code == 0) {
								t.showContentOnGrid(res.data.content, t.c.draft);
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
				
				//行双击事件
				layui.table.on('rowDouble(' + t.c.draft.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.id,
							type: 'draft'
						},
						success: function (res) {
							if (res.code == 0) {
								t.updateContentOfDetail(res.data);
								t.showItem('detail', 'draft');
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
			},
			loadTableOfOutbox: function() {
				var t = this;
				
				var loaded = t.c.outbox.loaded;
				if(t.c.outbox.loaded == 1) {
					return;
				}
				t.c.outbox.loaded = 1;
				
				// 初始化列表-发件箱
				layui.table.render({
					elem: '#' + t.c.outbox.id_table
					,url: '/api/inter/mail/searchForOutbox'
					,toolbar: '#toolbar_for_3'
					,defaultToolbar: ['filter']
					,height: 'full-20' // 最大高度减去其他容器已占有的高度差
					,limit : 50
					,limits : [50,100,200,500]
					,where: {}
					,cellMinWidth: 95
					,totalRow: true // 开启合计行，true开启，false关闭
					,page: true
					,request: {
						pageName: 'page',
						limitName: 'size'
					}
					,even: false // 开启隔行背景
					,totalRow: true
					,cols: [ [
							 {title:'', type:'checkbox', fixed:'left', unresize:true, width: 50}
							 ,{field:'title', width:300, title: '主题', align: 'center'}
							 ,{field:'receivers', width:200, title: '收件人', align: 'center'}
							 ,{field:'copyers', width:200, title: '抄送', align: 'center'}
							 ,{field:'tags', width:200, title: '邮件标签', align: 'center'}
							 ,{field:'extraFile', width:80, title: '附件', align: 'center'}
							 ,{field:'emergent', width:80, title: '紧急程度', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_Emergent.length; i++) {
										var option = t.c.MAP_DICT_Emergent[i];
										if (option.value == d.emergent) {
											return option.name;
										}
									}
									return ``;
								}
							 }
						   ] ]
					,done: function(res){
						
					}
					,error: function(res, msg){
						console.log(res, msg)
					}
				});

				// 工具栏事件-草稿箱
				layui.table.on('toolbar(' + t.c.outbox.filter_table + ')', function(obj){
					var id = obj.config.id;
					var checkStatus = layui.table.checkStatus(id);
					var datas = checkStatus.data;
					var othis = lay(this);

					switch(obj.event){
						case 'batch_delete':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("确定删除？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/deleteBatchFromOutbox',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
					};
				});
				
				//行单击事件
				layui.table.on('row(' + t.c.outbox.filter_table + ')', function(obj){
					var content = ``;
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.id,
							type: 'outbox'
						},
						success: function (res) {
							if (res.code == 0) {
								t.showContentOnGrid(res.data.content, t.c.outbox);
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
				
				//行双击事件
				layui.table.on('rowDouble(' + t.c.outbox.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.id,
							type: 'outbox'
						},
						success: function (res) {
							if (res.code == 0) {
								t.updateContentOfDetail(res.data);
								t.showItem('detail', 'outbox');
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
			},
			loadTableOfDustbin: function() {
				var t = this;
				
				var loaded = t.c.dustbin.loaded;
				if(t.c.dustbin.loaded == 1) {
					return;
				}
				t.c.dustbin.loaded = 1;
				
				// 初始化列表-垃圾箱
				layui.table.render({
					elem: '#' + t.c.dustbin.id_table
					,url: '/api/inter/mail/searchForDustbin'
					,toolbar: '#toolbar_for_4'
					,defaultToolbar: ['filter']
					,height: 'full-20' // 最大高度减去其他容器已占有的高度差
					,limit : 50
					,limits : [50,100,200,500]
					,where: {}
					,cellMinWidth: 95
					,totalRow: true // 开启合计行，true开启，false关闭
					,page: true
					,request: {
						pageName: 'page',
						limitName: 'size'
					}
					,even: false // 开启隔行背景
					,totalRow: true
					,cols: [ [
							 {title:'', type:'checkbox', fixed:'left', unresize:true, width: 50}
							 ,{field:'title', width:300, title: '主题', align: 'center'}
							 ,{field:'createUserId', width:200, title: '发件人', align: 'center'}
							 ,{field:'copyers', width:200, title: '抄送', align: 'center'}
							 ,{field:'tags', width:200, title: '邮件标签', align: 'center'}
							 ,{field:'extraFile', width:80, title: '附件', align: 'center'}
							 ,{field:'emergent', width:80, title: '紧急程度', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_Emergent.length; i++) {
										var option = t.c.MAP_DICT_Emergent[i];
										if (option.value == d.emergent) {
											return option.name;
										}
									}
									return ``;
								}
							 }
							 ,{field:'stateRead', width:80, title: '阅读状态', align: 'center', templet: function(d){
									for (var i = 0; i < t.c.MAP_DICT_StateRead.length; i++) {
										var option = t.c.MAP_DICT_StateRead[i];
										if (option.value == d.stateRead) {
											return option.name;
										}
									}
									return ``;
								}
							 }
						   ] ]
					,done: function(res){
						
					}
					,error: function(res, msg){
						console.log(res, msg)
					}
				});

				// 工具栏事件-垃圾箱
				layui.table.on('toolbar(' + t.c.dustbin.filter_table + ')', function(obj){
					var id = obj.config.id;
					var checkStatus = layui.table.checkStatus(id);
					var datas = checkStatus.data;
					var othis = lay(this);

					switch(obj.event){
						case 'batch_delete':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("删除后不可恢复，确定删除？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/deleteBatchFromDustbin',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
						case 'batch_reback':
						{
							if(datas.length == 0) {
								layer.alert('尚未选中数据');
							} else {
								var ids = '';
								for(var i = 0 ;i < datas.length; i++){
									ids += datas[i].id + ',';
								}
								layui.layer.confirm("确定恢复到收件箱？",{
									btn: ['确定', '取消']
								}, function (index) {
									var indexOfLoading = layer.load(1, {
										shade: [0.5,'#000000'] //0.1透明度的白色背景
									});
									$.ajax({
										type: "POST",
										url: '/api/inter/mail/rebackBatchFromDustbin',
										data: {ids: ids.substring(0, ids.length - 1)},
										success: function (data) {
											if (data.code == 0) {
												layer.msg(data.msg);
												layer.close(indexOfLoading);
											} else {
												layer.msg(data.msg);
											}
										}
									});
									layer.close(index);
								});
								return;
							}
							break;
						}
					};
				});
				
				//行单击事件
				layui.table.on('row(' + t.c.dustbin.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.mainId,
							type: 'dustbin'
						},
						success: function (res) {
							if (res.code == 0) {
								t.showContentOnGrid(res.data.content, t.c.dustbin);
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
				
				//行双击事件
				layui.table.on('rowDouble(' + t.c.dustbin.filter_table + ')', function(obj){
					$.ajax({
						type: "POST",
						url: '/api/inter/mail/detail',
						data: {
							id: obj.data.mainId,
							type: 'dustbin'
						},
						success: function (res) {
							if (res.code == 0) {
								t.updateContentOfDetail(res.data);
								t.showItem('detail', 'dustbin');
							} else {
								layer.msg(res.msg);
							}
						}
					});
				});
			},
			showContentOnGrid: function(content, obj) { // 在列表上显示详情
				var t = this;
				var domPanel = $('#' + obj.id_panel);
				
				if (obj.showContented == 0) {
					domPanel.find('div[data-filter="filter_grid_panel"]').height('calc(100% - 310px)'); // 容器高度缩小
					var domGrid = domPanel.find('div[lay-id="' + obj.id_table + '"]'); // 表格节点
					domGrid.height(domGrid.height() - 300); // 表格高度缩小300
					var domMainTable = domGrid.find('.layui-table-main'); // 主表节点
					domMainTable.height(domMainTable.height() - 300); // 主表高度缩小300
				}
				
				content = `<hr class="layui-bg-black">` + content;
				domPanel.find('div[data-filter="filter_content"]').html(content);
				domPanel.find('div[data-filter="filter_content"]').show();
				
				obj.showContented = 1;
			},
			matchValuesAfterModalSelectCheckbox: function(rowsSelected, extraData) {
				var t = this;
				
				var useIn = extraData.useIn;
				if (useIn == 'select_users_for_group') {
					var groupId = extraData.groupId;
					t.doAddUserToGroup(rowsSelected, groupId);
				} else if (useIn == 'select_receiver') {
					t.doUpdateUsersForReceiver(rowsSelected);
				} else if (useIn == 'select_copyer') {
					t.doUpdateUsersForCopyer(rowsSelected);
				} else if (useIn == 'select_tag') {
					t.doUpdateOptionsForTag(rowsSelected);
				}
			},
			doAddUserToGroup: function(rowsSelected, groupId) {
				var t = this;
				var indexOfLoading = layer.load(1, {
					shade: [0.5,'#000000'] //0.1透明度的白色背景
				});
				$.ajax({
					type: "POST",
					url: '/api/inter/mailGroup/addUsers',
					data: {
						groupId: groupId,
						userArr: JSON.stringify(rowsSelected)
					},
					success: function (res) {
						if (res.code == 0) {
							layer.msg(res.msg);
							t.loadDtreeGroup();
						} else {
							layer.msg(res.msg);
						}
						layer.close(indexOfLoading);
					}
				});
			},
			doUpdateUsersForReceiver: function(rowsSelected) {
				var t = this;
				t.c.selectedDatas_receiver = [];
				var h = ``;
				for (var i = 0; i < rowsSelected.length; i++) {
					var row = rowsSelected[i];
					var userId = row.userId;
					var userName = row.userName;
					t.c.selectedDatas_receiver.push({
						userId: userId,
						userName: userName
					});
					h += `<div class="person_single" data-user-id="` + userId + `" data-user-name="` + userName + `"><span>` + userId + `/` + userName + `</span>&nbsp;<i class="layui-icon layui-icon-reduce-circle" onclick="window.MailObj.doRemoveOption('` + userId + `', 'receiver')"></i></div>`;
				}
				$('#id_receivers').html(h);
			},
			doUpdateUsersForCopyer: function(rowsSelected) { // 更新抄送人
				var t = this;
				t.c.selectedDatas_copyer = [];
				var h = ``;
				for (var i = 0; i < rowsSelected.length; i++) {
					var row = rowsSelected[i];
					var userId = row.userId;
					var userName = row.userName;
					t.c.selectedDatas_copyer.push({
						userId: userId,
						userName: userName
					});
					h += `<div class="person_single" data-user-id="` + userId + `" data-user-name="` + userName + `"><span>` + userId + `/` + userName + `</span><i class="layui-icon" onclick="window.MailObj.doRemoveOption('` + userId + `', 'copyer')">&#x1007</i></div>`;
				}
				$('#id_copyers').html(h);
			},
			doUpdateOptionsForTag: function(rowsSelected) {
				var t = this;
				t.c.selectedDatas_tag = [];
				var h = ``;
				for (var i = 0; i < rowsSelected.length; i++) {
					var row = rowsSelected[i];
					var id = row.id;
					var name = row.name;
					t.c.selectedDatas_tag.push({
						id: id,
						name: name
					});
					h += `<div class="person_single" data-user-id="` + id + `" data-user-name="` + name + `"><span>` + name + `</span><i class="layui-icon" onclick="window.MailObj.doRemoveOption('` + id + `', 'tag')">&#x1007</i></div>`;
				}
				$('#id_tags').html(h);
			},
			doUpdateWriteOfTitle: function(title) {
				var t = this;
				$('#' + t.c.id_form_for_witer).find('#id_form_title').val(title);
			},
			doUpdateWriteOfEmergent: function(emergent) {
				var t = this;
				$('#' + t.c.id_form_for_witer).find('input[name="emergent"]').each(function(index, domEle){
					var value = $(this).val();
					if (value == emergent) {
						$(this).attr('checked', 'true');
					}
					layui.form.render();
				});
			},
			doUpdateWriteOfDraftId: function(draftId) {
				var t = this;
				t.c.draftId = draftId;
				
				// 初始化附件节点属性
				$('#id_input_file_multy_for_draft').attr('data-source-id', t.c.draftId);
				
				$('#' + t.c.id_form_for_witer).find('input[name="draftId"]').val(draftId);
			},
			doClearOption: function() {
				if (type == 'receiver') {
					this.doUpdateUsersForReceiver([]);
				} else if (type == 'copyer') {
					this.doUpdateUsersForCopyer([]);
				}
			},
			doRemoveOption: function(id, type) {
				var t = this;
				
				if (type == 'receiver') {
					for (var i = 0; i < t.c.selectedDatas_receiver.length; i++) {
						var row = t.c.selectedDatas_receiver[i];
						if (row.userId == id) {
							t.c.selectedDatas_receiver.splice(i, 1);
							break;
						}
					}
					t.doUpdateUsersForReceiver(t.c.selectedDatas_receiver);
				} else if (type == 'copyer') {
					for (var i = 0; i < t.c.selectedDatas_copyer.length; i++) {
						var row = t.c.selectedDatas_copyer[i];
						if (row.userId == id) {
							t.c.selectedDatas_copyer.splice(i, 1);
							break;
						}
					}
					t.doUpdateUsersForCopyer(t.c.selectedDatas_copyer);
				} else if (type == 'tag') {
					for (var i = 0; i < t.c.selectedDatas_tag.length; i++) {
						var row = t.c.selectedDatas_tag[i];
						if (row.id == id) {
							t.c.selectedDatas_tag.splice(i, 1);
							break;
						}
					}
					t.doUpdateOptionsForTag(selectedDatas_tag);
				}
			},
			/*
			 * 绑定选择收件人、抄送人或邮件标签
			 */
			bindModalSelector: function() {
				var t = this;
				
				$('i[data-filter="_select_option"]').on('click',function (e) {
					var dataType = $(this).attr('data-type');
					
					if (dataType == 'select_for_receivers') {
						layui.YsModal.init({modalKey: 'TS_UserInfo', type: 'checkbox', uniqueKey: 'userId', parentObj: t, selectedData: t.c.selectedDatas_receiver, extraData:{useIn: 'select_receiver'}});
					} else if (dataType == 'select_for_copyers') {
						layui.YsModal.init({modalKey: 'TS_UserInfo', type: 'checkbox', uniqueKey: 'userId', parentObj: t, selectedData: t.c.selectedDatas_copyer, extraData:{useIn: 'select_copyer'}});
					} else if (dataType == 'select_for_tags') {
						layui.YsModal.init({modalKey: 'MAIL_Tag', type: 'checkbox', uniqueKey: 'id', parentObj: t, selectedData: t.c.selectedDatas_tag, extraData:{useIn: 'select_tag'}});
					}
					return;
				});
			},
			updateContentOfDetail: function(data) {
				this.c.detail.data = data;
				$('#id_detail_title').html(data.title);
				$('#id_detail_extra_file').html(data.extraFile);
				$('#id_detail_sender').html(data.senderUserName + '[' + data.senderUserId + ']');
				$('#id_detail_time').html(data.createTime);
				$('#id_detail_receivers').html(data.receivers);
				$('#id_detail_content').html(data.content);
				$('#id_multy_file_for_detail').attr('data-source-id', data.id);
			},
			/*
			 * backType 点击返回时的类型
			 */
			showItem: function(type, backType) {
				var t = this;
				t.c.backType = backType;
				$('div[data-filter="filter_panel_right"]').each(function(index, domEle){
					var typeThis = $(this).attr('data-type');
					if(type == typeThis) {
						$(this).show();
					} else {
						$(this).hide();
					}
				});
				$('div[data-filter="filter_panel_left"]').each(function(index, domEle){
					var typeThis = $(this).attr('data-type');
					if(type == typeThis) {
						$(this).show();
					} else {
						$(this).hide();
					}
				});
				
				// 控制加载剩下的表格
				if (type == 'draft') {
					t.loadTableOfDraft();
				} else if (type == 'outbox') {
					t.loadTableOfOutbox();
				} else if (type == 'dustbin') {
					t.loadTableOfDustbin();
				}
				
				// 绑定详情页附件按钮
				if(type == 'detail') {
					console.log(222222);
					t.bindFileMultyOfDetail();
				}
			},
			bindClickBtn: function() {
				var t = this;
				
				layui.form.on('submit(form_submit_send_mail)', function(data){
					var indexOfLoading = layer.load(1, {
						shade: [0.5,'#000000'] //0.1透明度的白色背景
					});

					data.field['receiverArr'] = JSON.stringify(t.c.selectedDatas_receiver);
					data.field['copyerArr'] = JSON.stringify(t.c.selectedDatas_copyer);
					data.field['tagArr'] = JSON.stringify(t.c.selectedDatas_tag);
					
					/*
					 * 拼接正文
					 * 1、收件人格式:费玉清[00001],周杰伦[00002]
					 */
					var contentOfReceiver = ``;
					for (var i = 0; i < t.c.selectedDatas_receiver.length; i++) {
						var JO = t.c.selectedDatas_receiver[i];
						contentOfReceiver += JO.userName + `[` + JO.userId + `],`;
					}
					if(t.c.selectedDatas_receiver.length > 0) {
						contentOfReceiver = contentOfReceiver.substring(0, contentOfReceiver.length - 1);
					}
					var content
						= `<p><br /></p>`
						+ `<div style="background: #f3f1f1;padding:5px 6px;font-size: 14px;">`
							+ `<p style="margin:2px 0;"><b>发件人：</b>` + t.c.senderUserName + `[` + t.c.senderUserId + `];</p>`
							+ `<p style="margin:2px 0;"><b>发件时间：</b>` + new Date() + `;</p>`
							+ `<p style="margin:2px 0;"><b>收件人：</b>` + contentOfReceiver + `;</p>`
							+ `<p style="margin:2px 0;"><b>主题：</b>` + data.field['title'] + `;</p>`
						+ `</div>`
						+ `<div style="font-family: Arial Narrow;padding:2px 0 2px 0;">`
							+ `<hr style="border-top: 1px dotted;margin: 10px 1px;">`
						+ `</div>`;
					data.field['detail'] = data.field['detail'] + content;
					
					$.post('/api/inter/mail/sendMail', data.field, function(res){
						if (res.code == 0) {
							layer.msg('操作成功');
							layer.close(indexOfLoading);
							
							// 初始化草稿箱
							t.initDraft();
						} else {
							layer.close(indexOfLoading);
							layer.msg(res.msg);
						}
					});
					return false;
				});
				
				// 绑定按钮-存草稿
				layui.form.on('submit(form_submit_save_draft)', function(data){
					var indexOfLoading = layer.load(1, {
						shade: [0.5,'#000000'] //0.1透明度的白色背景
					});

					data.field['type'] = 2;
					data.field['receiverArr'] = JSON.stringify(t.c.selectedDatas_receiver);
					data.field['copyerArr'] = JSON.stringify(t.c.selectedDatas_copyer);
					data.field['tagArr'] = JSON.stringify(t.c.selectedDatas_tag);
					$.post('/api/inter/mailDraft/save', data.field, function(res){
						if (res.code == 0) {
							layer.msg('操作成功');
							layer.close(indexOfLoading);
							
							// 初始化草稿箱
							t.initDraft();
						} else {
							layer.close(indexOfLoading);
							layer.msg(res.msg);
						}
					});
					return false;
				});
				
				// 绑定按钮-搜索
				layui.form.on('submit(form_submit_search_table)', function(data){
					
					var indexOfLoading = layer.load(1, {
						shade: [0.5,'#000000'] //0.1透明度的白色背景
					});
					
					var conditionsRes = [];
					
					if (data.field.title) { // 标题
						conditionsRes.push({'rangeType': 't_bothlike', 'value': data.field.title, 'field': 'B.Title'});
					}
					if (data.field.detail) { // 正文
						conditionsRes.push({'rangeType': 't_bothlike', 'value': data.field.detail, 'field': 'B.Detail'});
					}
					if (data.field.sender) { // 发件人
						conditionsRes.push({'rangeType': 't_bothlike', 'value': data.field.sender, 'field': 'C.UserId'});
					}
					if (data.field.receivers) { // 收件人
						conditionsRes.push({'rangeType': 't_bothlike', 'value': data.field.receivers, 'field': 'C.UserId'});
					}
					if (data.field.tags) { // 邮件标签
						conditionsRes.push({'rangeType': 't_bothlike', 'value': data.field.tags, 'field': 'B.Tags'});
					}
					if (data.field.sendTime) { // 发送时间
						conditionsRes.push({'rangeType': 't_between', 'value': data.field.sendTime, 'field': 'B.CreateTime'});
					}
					if (data.field.emergent) { // 紧急程度
						conditionsRes.push({'rangeType': 't_system', 'value': data.field.emergent, 'field': 'B.Emergent'});
					}
					if (data.field.stateRead) { // 邮件状态
						conditionsRes.push({'rangeType': 't_system', 'value': data.field.stateRead, 'field': 'A.StateRead'});
					}
					
					var where = {'conditions': JSON.stringify(conditionsRes)};
					
					// 根据不同表单ID，重新加载不同表格
					var id_table = ''; // 表格ID
					var id_form = data.form.id;
					if (id_form == 'id_form_search_table_for_receive') {
						id_table = t.c.inbox.id_table;
					} else if (id_form == 'id_form_search_table_for_draft') {
						id_table = t.c.draft.id_table;
					} else if (id_form == 'id_form_search_table_for_sender') {
						id_table = t.c.outbox.id_table;
					} else if (id_form == 'id_form_search_table_for_rabish') {
						id_table = t.c.dustbin.id_table;
					}
					layui.table.reload(id_table, {
						page: {
							curr: 1 //重新从第 1 页开始
						},
						where: where
					})
					layer.close(indexOfLoading);
					return;
				});
				
				// 绑定按钮-	清空搜索条件
				layui.form.on('submit(form_clear_search_table)', function(data){
					$("#" + data.form.id)[0].reset();
					return;
				});
				
				t.bindClickBtnOfWrite(); // 绑定新建邮件页的按钮点击
				
				t.bindClickBtnOfDetail(); // 绑定详情页的按钮点击
			},
			bindClickBtnOfWrite: function() {
				var t = this;
				$('div[data-filter="filter_write_close"]').on('click',function (e) {
					t.showItem(t.c.backType, t.c.backType);
				});
			},
			bindClickBtnOfDetail: function() {
				var t = this;
				$('a[data-filter="filter_detail_btn"]').on('click',function (e) {
					var type = $(this).attr('data-type');
					if(type == 'back') {
						t.showItem(t.c.backType);
					} else if(type == 'reply') {
						// 更新收件人
						t.doUpdateUsersForReceiver([{'userId': t.c.detail.data.senderUserId, 'userName': t.c.detail.data.senderUserName}]);
						// 更新抄送人
						t.doUpdateUsersForCopyer([]);
						// 更新标签
						t.doUpdateOptionsForTag([]);
						// 更新标题
						t.doUpdateWriteOfTitle('回复：' + t.c.detail.data.title);
						// 更新紧急程度
						t.doUpdateWriteOfEmergent(1);
						// 更新正文
						t.initHypeTextEditor(t.c.detail.data.content + '<p><br /></p>');
						
						// 显示新建邮件
						t.showItem('write', t.c.backType);
					} else if(type == 'transfer') {
						// 更新收件人
						t.doUpdateUsersForReceiver([]);
						// 更新抄送人
						t.doUpdateUsersForCopyer([]);
						// 更新标签
						t.doUpdateOptionsForTag([]);
						// 更新标题
						t.doUpdateWriteOfTitle('转发：' + t.c.detail.data.title);
						// 更新紧急程度
						t.doUpdateWriteOfEmergent(1);
						// 更新正文
						t.initHypeTextEditor(t.c.detail.data.content + '<p><br /></p>');
						
						// 显示新建邮件
						t.showItem('write', t.c.backType);
					} else if(type == 'delete') {
						layer.confirm('确定删除？ ', {
							btn: ['确定','取消'] //按钮
						}, function(){
							var indexOfLoading = layer.load(1, {
								shade: [0.5,'#000000'] //0.1透明度的白色背景
							});
							$.ajax({
								type: "POST",
								url: '/api/inter/mail/delete',
								data: {
									id: t.c.detail.data.id,
									type: t.c.detail.data.type
								},
								success: function (res) {
									layer.msg(res.msg);
									if (res.code == 0) {
										setTimeout(function(){
											t.showItem(t.c.detail.data.type);
										}, 1000);
									} else {
										layer.msg(res.msg);
									}
									layer.close(indexOfLoading);
								}
							});
						}, function(){}
						);
					}
				});
			},
			initHypeTextEditor: function(content) {
				var t = this;
				
				$('#' + t.c.id_form_for_witer).find('textarea[lay-filter="hypeTextEditor"]').each(function(index, domEle){
					var id = $(this).attr('id');
					var url = window.location.href;
					var arrUrl = url.split("//");
					var start = arrUrl[1].indexOf("/");
					var preUrl = 'http://' + arrUrl[1].substring(0, start);
					var config = {
						"width": "100%",
						"height": 450,
						"resizeType": 0,
						"autoHeightMode": false,
						"items": [
							'source', '|',
							'undo', 'redo', '|',
							'preview', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|',
							'justifyleft', 'justifycenter', 'justifyright',
							'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'clearhtml', 'quickformat', 'selectall', '/',
							'formatblock', 'fontname', 'fontsize', '|',
							'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|',
							'image', 'multiimage', 'insertfile', 'link', 'unlink'
						],
						"allowImageRemote": false,
						"uploadJson": preUrl + "/api/outer/upload/uploadfileForEditor",
						"filePostName": "fileStream",
						"formatUploadUrl": false,
						afterBlur: function () {
							this.sync();
						}
					};
					if (!t.editor) {
						t.editor = KindEditor.create('#' + id, config);
					}
					var code = $(this).attr('name');
					t.editor.html(content);
					t.editor.sync();
				});
			},
			bindFormItem: function() {

				// 初始化日期选择框（YYYY-MM-DD）- 收件箱搜索
				$('#id_form_search_table_for_receive').find('.search-input').each(function(){
					var dataInputType = $(this).attr('data-input-type');
					if(dataInputType && dataInputType == 'date_day') {
						var myDate = new Date();
						layui.laydate.render({
							elem: this
							, type: 'date'
							, range: '~'
							, calendar: true
							, btns: ['clear', 'confirm', 'now']
							, done: function (value, date) {
							}
						});
					}
				});
			},
			bindFileMultyOfDraft: function() {
				var t = this;
				$('#id_input_file_multy_for_draft').on('click',function (e) {
					var dom = this;
					layui.YsMultyFile.init({dom: dom, btnDisable: false, extraParam:{parentObj: t}});
				});
			},
			bindFileMultyOfDetail: function() {
				var t = this;
				$('#id_multy_file_for_detail').on('click',function (e) {
					var dom = this;
					layui.YsMultyFile.init({dom: dom, btnDisable: false, extraParam:{parentObj: t}});
				});
			},
			saveDraftOnly: function() {
				var t = this;
				
				var formData = $('#' + t.c.id_form_for_witer).serialize();
				formData = formData
					+ "&type=1"
					+ "&receiverArr=" + JSON.stringify(t.c.selectedDatas_receiver)
					+ "&copyerArr=" + JSON.stringify(t.c.selectedDatas_copyer)
					+ "&tagArr=" + JSON.stringify(t.c.selectedDatas_tag);
				$.post('/api/inter/mail/saveDraft', formData, function(res){
					if (res.code != 0) {
						layer.msg(res.msg);
					}
				});
			},
			init:function (c) {
				this.f(c);
				this.load();
				return object;
			}
		};
	exports('MailObj', object);
});